namespace ResumableDownload.View.Converters
{
    using System;
    using System.Globalization;
    using System.Windows;
    using System.Windows.Data;
    using WP7Contrib.Services.DownloadManager;

    public sealed class FileLengthToStringConverter : IValueConverter
    {
        private const int MegaByte = 1048576;
        private const int GigaByte = 1073741824;

        public static NumberFormatInfo nfi;
        public static NumberFormatInfo nfiPercentage;

        public readonly string ByteSizeFormat = "{0} bytes";
        public readonly string MegaByteSizeFormat = "{0} Mb";
        public readonly string GigaByteSizeFormat = "{0} Gb";

        static FileLengthToStringConverter()
        {
            nfi = (NumberFormatInfo)CultureInfo.CurrentUICulture.NumberFormat.Clone();
            nfi.NumberDecimalDigits = 2;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null || value == DependencyProperty.UnsetValue)
            {
                return DependencyProperty.UnsetValue;
            }
            var contentLength = System.Convert.ToDouble(value);

            if (Equals(contentLength, 0))
            {
                return DependencyProperty.UnsetValue;
            }

            var format = ByteSizeFormat;
            var isGb = ((contentLength / GigaByte) > 0.5);
            var isMb = ((contentLength / MegaByte) > 0.5);
            
            if (isGb || Equals(contentLength, 0))
            {
                format = GigaByteSizeFormat;
                nfi.NumberDecimalDigits = 3;
                contentLength = contentLength / GigaByte;
            }
            else if (isMb)
            {
                format = MegaByteSizeFormat;
                nfi.NumberDecimalDigits = 2;
                contentLength = contentLength / MegaByte;
            }
            else
            {
                format = ByteSizeFormat;
                nfi.NumberDecimalDigits = 0;
            }

            return string.Format(format, contentLength.ToString("N", nfi));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return DependencyProperty.UnsetValue;
        }
    }
}